/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controllers;

import domain.User;
import domain.Video;
import domain.VideoCategory;
import exceptions.GeneralServiceException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.validation.constraints.Size;
import service.impl.VideoCategoryServiceImpl;
import service.impl.VideoServiceImpl;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import java.security.Principal;
import java.util.Calendar;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.myfaces.custom.fileupload.UploadedFile;
import org.hibernate.validator.constraints.NotEmpty;
import service.impl.UserServiceImpl;

/**
 *
 * @author yuyok
 */
@ManagedBean(name = "video")
@RequestScoped
public class VideoManagerController {
    
    @EJB
    private VideoCategoryServiceImpl videoCategoryService;
    @EJB
    private VideoServiceImpl videoService;
    @EJB
    private UserServiceImpl userService;
    @ManagedProperty("#{param.id}")
    private String id;
    private String categoryName;
    private String categoryNameToChange;
    private UploadedFile uploadedFile;
    private String fileName;
    private String description;
    @Size(min = 4, message = "at least 4 symbols")
    private String videoName;
    @Size(min = 4, message = "at least 4 symbols")
    private String videoDescription;
    
    public String getVideoDescription() {
        return videoDescription;
    }
    
    public void setVideoDescription(String videoDescription) {
        this.videoDescription = videoDescription;
    }
    
    public String getVideoName() {
        return videoName;
    }
    
    public void setVideoName(String videoName) {
        this.videoName = videoName;
    }
    
    public String getDescription() {
        return description;
    }
    
    public void setDescription(String description) {
        this.description = description;
    }
    
    public String getCategoryNameToChange() {
        return categoryNameToChange;
    }
    
    public void setCategoryNameToChange(String categoryNameToChange) {
        this.categoryNameToChange = categoryNameToChange;
    }
    
    public String getCategoryName() {
        return categoryName;
    }
    
    public void setCategoryName(String categoryName) {
        this.categoryName = categoryName;
    }
    
    public String getId() {
        return id;
    }
    
    public void setId(String id) {
        this.id = id;
    }
    
    public List<VideoCategory> getAllVideoCategories() {
        return videoCategoryService.getAllVideoCategories();
    }
    
    public String addNewCategory() {
        String result;
        VideoCategory vc = new VideoCategory(categoryName);
        try {
            videoCategoryService.save(vc);
            result = "categories";
        } catch (GeneralServiceException ex) {
            Logger.getLogger(VideoManagerController.class.getName()).log(Level.SEVERE, null, ex);
            result = "error";
        }
        return result;
    }
    
    public String changeCategoryName() {
        String result;
        
        Long vcId = new Long(id);
        
        VideoCategory vc = videoCategoryService.getEntityById(vcId);
        vc.setCategoryName(categoryNameToChange);
        try {
            videoCategoryService.save(vc);
            result = "categories";
        } catch (GeneralServiceException ex) {
            Logger.getLogger(VideoManagerController.class.getName()).log(Level.SEVERE, null, ex);
            result = "error";
        }
        
        return result;
    }
    
    public String deleteCategory() {
        String result;
        
        Long vcId = new Long(id);
        
        videoCategoryService.delEntityById(vcId);
        result = "categories";
        
        return result;
    }
    
    public String gotoAddNewCategory() {
        return "addcategory";
    }
    
    public String gotoChangeCategory() {
        return "changecategory";
    }
    
    public void uploadFile() {

        // Just to demonstrate what information you can get from the uploaded file.
        System.out.println("File type: " + uploadedFile.getContentType());
        System.out.println("File name: " + uploadedFile.getName());
        System.out.println("File size: " + uploadedFile.getSize() + " bytes");

        // Prepare filename prefix and suffix for an unique filename in upload folder.
        String prefix = FilenameUtils.getBaseName(uploadedFile.getName());
        String suffix = FilenameUtils.getExtension(uploadedFile.getName());

        // Prepare file and outputstream.
        File file = null;
        OutputStream output = null;
        
        try {
            // Create file with unique name in upload folder and write to it.
            file = File.createTempFile(prefix + "_", "." + suffix, new File("/home/yuyok/uploads"));
            output = new FileOutputStream(file);
            IOUtils.copy(uploadedFile.getInputStream(), output);
            fileName = file.getName();
            
            Principal principal = FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal();
            User user = userService.getUserByLogin(principal.getName());
            
            VideoCategory vc = videoCategoryService.getVideoCategoryByName(categoryName);
            
            Video video = new Video();
            video.setAddedDate(Calendar.getInstance());
            video.setName(videoName);
            video.setUrl(fileName);
            video.setIsEnable(true);
            video.setDescription(videoDescription);
            video.setUser(user);
            
            try {
                videoService.save(video);
                vc.addVideo(video);
//                user.addVideo(video);
                videoCategoryService.save(vc);
//                userService.save(user);
            } catch (GeneralServiceException ex) {
                Logger.getLogger(VideoManagerController.class.getName()).log(Level.SEVERE, null, ex);
            }
            // Show succes message.
            FacesContext.getCurrentInstance().addMessage("uploadForm", new FacesMessage(
                    FacesMessage.SEVERITY_INFO, "File upload succeed!", null));
            
        } catch (IOException e) {
            // Cleanup.
            if (file != null) {
                file.delete();
            }

            // Show error message.
            FacesContext.getCurrentInstance().addMessage("uploadForm", new FacesMessage(
                    FacesMessage.SEVERITY_ERROR, "File upload failed with I/O error.", null));

            // Always log stacktraces (with a real logger).
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(output);
        }
    }
    
    public UploadedFile getUploadedFile() {
        return uploadedFile;
    }
    
    public String getFileName() {
        return fileName;
    }

    // Setters ------------------------------------------------------------------------------------
    public void setUploadedFile(UploadedFile uploadedFile) {
        this.uploadedFile = uploadedFile;
    }
}
